import { getQuery } from 'h3';
import mongoose from 'mongoose';
import { ArticleModel } from '~/server/models/article.model';

// 删除文章
export default defineEventHandler(async (event): Promise<any> => {
	const query = getQuery(event);
	const ids: string[] = query.id ? String(query.id).split(',') : [];

	if (!ids.length) {
		return { code: 0, message: '缺少 id 参数' };
	}

	// 转换为 ObjectId
	const objectIds = ids
		.map((id) => {
			try {
				return new mongoose.Types.ObjectId(id);
			} catch {
				return null;
			}
		})
		.filter(Boolean);

	if (!objectIds.length) {
		return { code: 0, message: 'id 参数格式错误' };
	}

	try {
		const result = await ArticleModel.deleteMany({ _id: { $in: objectIds } });

		return {
			code: 1,
			message: `成功删除 ${result.deletedCount} 篇文章`,
			deletedCount: result.deletedCount,
		};
	} catch (error: any) {
		return { code: 0, error: error.message };
	}
});
